package server.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class ServerXmlUtil {
    private static final String SERVER_XML_PATH = System.getProperty("user.dir") + File.separator + "conf" + File.separator + "server.xml";
    private static ServerXml serverXml = null;

    public static ServerXml getServerXml() throws DocumentException {
        if (serverXml == null)
            serverXml = parse();
        return serverXml;
    }

    public static void destroy() {
        serverXml = null;
    }

    private static ServerXml parse() throws DocumentException {
        SAXReader saxReader = new SAXReader();
        File file = new File(SERVER_XML_PATH);
        Document document = saxReader.read(file);
        Element server = document.getRootElement();
        ServerXml serverXml = new ServerXml();

        serverXml.setShutdownPort(Integer.parseInt(server.attributeValue("port")));
        serverXml.setShutdownCmd(server.attributeValue("shutdown"));

        List<Element> connector = server.elements("Connector");
        if (connector != null && connector.size() >= 1) {
            Element element = connector.get(connector.size() - 1);
            serverXml.setServerPort(Integer.parseInt(element.attributeValue("port")));
            serverXml.setConnectionTimeout(Integer.parseInt(element.attributeValue("connectionTimeout")));
            serverXml.setAcceptCount(Integer.parseInt(element.attributeValue("acceptCount")));
            serverXml.setMaxThreads(Integer.parseInt(element.attributeValue("maxThreads")));
            serverXml.setMinThreads(Integer.parseInt(element.attributeValue("minThreads")));
        }

        List<Element> loader = server.elements("Loader");
        if (loader != null && loader.size() >= 1) {
            Element element = loader.get(loader.size() - 1);
            serverXml.setReloadable(Boolean.parseBoolean(element.attributeValue("reloadable")));
            serverXml.setCheckInterval(Integer.parseInt(element.attributeValue("checkInterval")));
        }

        return serverXml;
    }

}
